package com.walker.kuyun.util

import android.util.Base64
import com.blankj.utilcode.util.FileIOUtils
import com.blankj.utilcode.util.FileUtils
import com.walker.kuyun.App
import org.jsoup.Connection
import org.jsoup.Jsoup
import org.jsoup.helper.HttpConnection
import org.jsoup.nodes.Document

object JsoupUtil {
    private val connection = HttpConnection()
        .timeout(30000)
        .header("Connection", "close")
        .header(
            "Accept",
            "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8"
        )
        .header("Accept-Encoding", "gzip, deflate, sdch")
        .header("Accept-Language", "zh-CN,zh;q=0.8")
        .header(
            "User-Agent",
            "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36"
        )
        .method(Connection.Method.GET)
        .followRedirects(true)

    fun getDocument(url: String): Document {
        val cacheDir = App.getApp().getExternalFilesDir(null)!!.path
        val startSpiltIndex = url.indexOf("//") + 2
        val startSpiltIndex2 = url.indexOf("/", startSpiltIndex, true)
        val finalUrl = if (startSpiltIndex > startSpiltIndex2) {
            // 表示没找到相关路径
            url.substring(startSpiltIndex)
        } else {
            url.substring(startSpiltIndex2)
        }
        //提取请求路径
        val decodeUrl = String(Base64.encode(finalUrl.toByteArray(), Base64.DEFAULT))

        val cacheFile = "$cacheDir/$decodeUrl"
        val isExist = FileUtils.isFileExists(cacheFile) && FileUtils.getLength(cacheFile) > 0

        return if (isExist) {
            Jsoup.parse(FileIOUtils.readFile2String(cacheFile))
        } else {
            val body =
                connection.url(url)
                    .execute()
                    .body()
            FileIOUtils.writeFileFromString(cacheFile, body, false)
            Jsoup.parse(body)
        }
    }

}